package com.newcapec.shiro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.newcapec.shiro.constant.CommonConstant;
import com.newcapec.shiro.dao.ResourcesDao;
import com.newcapec.shiro.entity.Resources;
import com.newcapec.shiro.service.ResourcesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ResourcesServiceImpl implements ResourcesService {

    @Autowired
    private ResourcesDao resourcesDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Resources entity) {
        resourcesDao.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(Resources entity) {
        resourcesDao.update(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(Integer id) {
        resourcesDao.delete(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeBatch(Integer[] id) {
        resourcesDao.deleteBatch(id);
    }

    @Override
    public Resources findById(Integer id) {
        return resourcesDao.selectById(id);
    }

    @Override
    public Map<String, Object> find(Integer pageNum, Integer pageSize, Resources entity) {
        PageHelper.startPage(pageNum, pageSize);
        List<Resources> list = resourcesDao.select(entity);
        PageInfo<Resources> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put(CommonConstant.PAGE_LIST, list);
        map.put(CommonConstant.PAGE_TOTAL, total);
        return map;
    }

    @Override
    public List<Resources> findAll() {
        return resourcesDao.selectAll();
    }

    @Override
    public List<Resources> findTree() {
        List<Resources> list = findAll();
        return toTree(list);
    }

    @Override
    @Cacheable(value = "user:login:cache", key = "'permission'+#userId", unless = "#result eq null")
    public List<Resources> findByUserId(Integer userId) {
        return resourcesDao.selectByUserId(userId);
    }

    public List<Resources> toTree(List<Resources> list){
        List<Resources> tree = new ArrayList<>();
        for (Resources resources : list) {
            if(resources.getPid() == null || resources.getPid().equals(0)){
                tree.add(resources);
            }else{
                for (Resources r : list) {
                    if(resources.getPid().equals(r.getId())){
                        r.getChildren().add(resources);
                    }
                }
            }
        }
        return tree;
    }
}
